package com.jd.threed.阻塞队列原理;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用condition 实现
 */
public class BlockingQueue2 {



    private Queue queue;

    private int max = 16;

    private ReentrantLock reentrantLock = new ReentrantLock();

    // 不是空的
    private Condition notEmpty = reentrantLock.newCondition();

    private Condition notFull = reentrantLock.newCondition();



    public BlockingQueue2(int size) {

        this.max = size;

        queue = new LinkedList();
    }


    public void put (Object o) throws InterruptedException {
        reentrantLock.lock();
        System.out.println(Thread.currentThread().getName()+"获取到了锁");

        try {
            while (queue.size() == max) {
                notFull.await();
            }
            queue.add(o);
            notEmpty.signalAll();// 通知消费者疯狂消费
        } finally {
            reentrantLock.unlock();
        }

    }

    public void take() throws InterruptedException {
        try {
            reentrantLock.lock();
            while (queue.size() == 0) {
                notEmpty.await();
            }
            queue.poll();
            notFull.signalAll(); // 通知生产者疯狂生产
        } finally {
            reentrantLock.unlock();
        }

    }



    public static void main(String[] args) throws InterruptedException {
        BlockingQueue2 queue2 = new BlockingQueue2(1);
        queue2.put(new Object());
        queue2.put(new Object());




    }
}
